package indi.lqzhi.basic.tools.mvvm;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import com.blankj.utilcode.util.ThreadUtils;



public class SafeLiveData<T> extends MutableLiveData<T> {

    public SafeLiveData() {
    }

    public SafeLiveData(T value) { fromValue(value); }

    public void fromValue(T value) {
        //错误的值就返回
        if (value == null){
            return;
        }
        if (ThreadUtils.isMainThread()){
            super.setValue(value);
        }else{
            super.postValue(value);
        }
    }

    @NonNull
    public T toValue(@NonNull  T defaultValue) {
        return super.getValue() == null ? defaultValue : super.getValue();
    }

    /**
     * 创建LiveData
     * @param o 对象
     * @return LiveData
     */
    public static <T> SafeLiveData<T> create(T o){
        return new SafeLiveData<>(o);
    }

    /**
     * 创建个空的LiveData
     * @return LiveData
     */
    public static <T> SafeLiveData<T> create(){
        return new SafeLiveData<>();
    }



}
